/*******************************************************
> Copyright (C) 2024 ==IOT== All rights reserved.
> File Name: 2.c
> Author: wyf
> Website:www.lv1.org
> Created Time: 2024年08月05日 星期一 16时50分25秒
***************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <assert.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct msgbuf
{
	long mtype;
	char mtext[50];
};
typedef struct stu{
	int id;
	char name[20];
	int age;
	struct stu *Next;
}STU;
int main(int argc, const char* argv[])
{
	key_t key = 0;
	int msgid = 0;
	int ret = 0;

	key = ftok("./",1);
	if(key == -1)
	{
		perror("ftok");
		exit(-1);
	}


	msgid = msgget(key,IPC_CREAT|0666);
	if(msgid == -1)
	{
		perror("msgget");
		exit(-1);
	}
//-------------------------------------------------------B进程从队列里面读取链表信息----------------------------------------------
	// 接收队列
    struct msgbuf msg;
    while (1) 
	{
        
		ret = msgrcv(msgid, &msg, sizeof(msg.mtext), 1, 0);
        if (ret == -1) {
            perror("msgrcv");
            exit(-1);
        }

        // 检查是否为结束标志
        if (strcmp(msg.mtext, "END") == 0) {
            break;
        }
		// 使用 memcpy 将消息缓冲区的数据复制到链表节点结构体
        STU node;
        memcpy(&node, msg.mtext, sizeof(node));
        printf("编号：%d 姓名: %s 年龄: %d\n", node.id, node.name, node.age);
    
	}

	
	printf("消息队列数据接收完成！\n");	
//----------------------------------------------------------------------------------------------------------------------









//-------------------------------------------------读取完再告诉A进程一句话---------------------------------------------
	struct msgbuf data;
	memset(&data,0,sizeof(struct msgbuf));
	data.mtype = 2;
	strcpy(data.mtext,"我读完了。");

	ret = msgsnd(msgid,&data,sizeof(struct msgbuf) - sizeof(long),0);
	if(ret == -1)
	{
		perror("msgsnd");
		exit(-1);
	}

//---------------------------------------------------------------------------------------------------------------------------

    return 0;
}


